package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;


@Service
@Slf4j
@RequiredArgsConstructor
public class ArticleSearchServiceImpl implements ArticleSearchService {

    private final RestHighLevelClient client;

    private final ApUserSearchService apUserSearchService;

    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        log.info("es分页搜索：{}", dto);
        // 检查参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        //异步调用添加搜索记录
        if (user != null && dto.getFromIndex() == 0) {
           apUserSearchService.insert(user.getId(), dto.getSearchWords());
        }

        // 1、准备请求，并指定索引库
        SearchRequest request = new SearchRequest("app_info_article");

        // 2、准备DSL
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 按照关键字搜索
        if (StringUtils.isNotBlank(dto.getSearchWords())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
            boolQueryBuilder.must(QueryBuilders.matchQuery("content", dto.getSearchWords()));
        }

        // 查询小于minBehotTime
        if (dto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime")
                    .lt(dto.getMinBehotTime().getTime()));
        }
        // 分页
        request.source().query(boolQueryBuilder).from(0)
                .size(dto.getPageSize());

        // 按照发布时间倒序
        request.source().sort("publishTime", SortOrder.DESC);

        // 设置高亮 title
        request.source().highlighter(SearchSourceBuilder.highlight()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        // 3、执行查询
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        // 4、结果封装返回
        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            Map map = JSON.parseObject(source, Map.class);
            Map<String, HighlightField> hfs = hit.getHighlightFields();
            // 处理高亮
            if (hfs != null && hfs.size() > 0) {
                // 如果有高亮字段，获取title的高亮结果
                Text[] titles = hfs.get("title").getFragments();
                String title = StringUtils.join(titles);
                // 高亮标题
                map.put("h_title", title);
            } else {
                // 原始标题
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }


        return ResponseResult.okResult(list);
    }
}
